/*
 * Golazo MA4
 * Copyright (C) 2008 Golazo MASHUP AWARD 4th team.
 * http://code.google.com/p/golazo/
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * serverload
 */
function serverload() {

  // ignore
  Jaxer.response.setClientFramework();

  // dispatch 
  Golazo.dispatch(function(request, response, session) {

    // 私は誰か
    var me = Golazo.User.find(session.get('me'));
	if (!me)
	  return $('#signin')
	    .layout(/*me*/)
		.gpsone();

    // GPS の緯度
    var lat = request.data.lat;
	if (typeof(lat) !== 'undefined')
	  lat = ''+Golazo.Geo.dmsToDegree(lat);

    // GPS の経度
    var lon = request.data.lon;
	if (typeof(lon) !== 'undefined')
	  lon = ''+Golazo.Geo.dmsToDegree(lon);
	
	if (lat && lon) {
	  
	  var log;
	  try {
        
        // ログを記録する
		log = new Golazo.UserLog(me);
        log.latitude = lat;
        log.longitude = lon;
        log.save();

      } catch (e) {
        throw new Error(''+e);
      }
	}

    // 現在地の緯度
    var latitude = lat || request.data.latitude;
    if (!Golazo.Action.checkLatitude(latitude))
  	  return $('#where')
	    .layout(me)
		.gpsone();

    // 現在地の経度
    var longitude = lon || request.data.longitude;
    if (!Golazo.Action.checkLongitude(longitude))
  	  return $('#where')
	    .layout(me)
		.gpsone();

    // 現在地の高さ
	var altitude = request.data.altitude;
    if (typeof(altitude) !== 'undefined') {
	  if (!Golazo.Action.checkAltitude(altitude))
	    throw new Error('(altitude)');
      altitude = parseInt(altitude, 10);
	}

    // メモの表示位置
    var startIndex = request.data.startIndex;
	if (!Golazo.checkDigit(startIndex))
	  startIndex = 1;
	else
	  startIndex = parseInt(startIndex, 10);
	if (startIndex < 1)
	  startIndex = 1;

    $('#form_startIndex')
      .val(startIndex);

    // メモの総件数
    var totalResults = Golazo.Action.countByMe(me, {});

    // メモを検索する
    var actions = Golazo.Action.findAllByMe(me, startIndex - 1, 1, {
      where: { latitude: latitude, longitude: longitude	}
	});

    if (actions.length == 0)
      $('#summary')
        .text('現在地から最も近いココメモが見つかりませんでした。');

    // メモをリスト表示する
	actions.forEach(function(action) {

      if (typeof(altitude) === 'undefined')
        altitude = action.altitude;

      var map = $('<p />')
	    .attr('align', 'center');
	  
	  $('<img />')
	    .attr('width', 230)
		.attr('height', 172)
		.staticmaps(action.latitude, action.longitude, altitude)
		.appendTo(map);

      var note = $('<p />')
		.text(action.note);

      $('<div />')
	    .append(map)
		.append(note)
		.appendTo('#actions');
    });

    var action = actions[0];

    if (typeof(altitude) === 'undefined')
      altitude = Golazo.WHERE_TOKYO.altitude;

    // 前のココメモ
	if (startIndex > 1 && startIndex <= totalResults) {
		
	  $('a.prev')
        .attr('href', '/ez/me.html?' + $.param({
		  startIndex: startIndex - 1,
		  latitude: latitude,
		  longitude: longitude
		}));
	
	} else {
		
	  $('a.prev').each(function() {
	    $(this)
		  .before(this.childNodes)
		  .remove();
	  });
	}

    // 次のココメモ
	if (startIndex < totalResults) {
	  
	  $('a.next')
        .attr('href', '/ez/me.html?' + $.param({
		  startIndex: startIndex + 1,
  		  latitude: latitude,
		  longitude: longitude
		}));
	
	} else {
	  
	  $('a.next').each(function() {
	    $(this)
		  .before(this.childNodes)
		  .remove();
	  });
	}
	
    // ココメモの登録
    $('a.add')
      .attr('href', '/ez/add.html?' + $.param({
		startIndex: startIndex,
  		latitude: latitude,
		longitude: longitude
	  }));

    // 地図の拡大
	if (action && Golazo.Action.checkAltitude(altitude + 1)) {
	  
	  $('a.in')
        .attr('href', '/ez/me.html?' + $.param({
		  startIndex: startIndex,
  		  latitude: latitude,
		  longitude: longitude,
		  altitude: altitude + 1
		}));
	
	} else {
	  
	  $('a.in').each(function() {
	    $(this)
		  .before(this.childNodes)
		  .remove();
	  });
	}

    // 地図の縮小
	if (action && Golazo.Action.checkAltitude(altitude - 1)) {
	  
	  $('a.out')
        .attr('href', '/ez/me.html?' + $.param({
		  startIndex: startIndex,
  		  latitude: latitude,
		  longitude: longitude,
		  altitude: altitude - 1
		}));
	
	} else {
	  
	  $('a.out').each(function() {
	    $(this)
		  .before(this.childNodes)
		  .remove();
	  });
	}

    // 乗換案内
    if (action) {
	
	  $('a.transit')
        .attr('href', 'http://www.google.co.jp/transit?' + $.param({
		  saddr: latitude + ',' + longitude,
		  daddr: action.latitude + ',' + action.longitude
		}));
	
	} else {
	  
	  $('a.transit').each(function() {
	    $(this)
		  .before(this.childNodes)
		  .remove();
	  });
	}

    return $('#succeeded')
	  .layout(me)
	  .gpsone();
  });
};

/**
 * load
function load(layout) {
};
load.runat = 'client';
 */
